const mongoose = require("../db");
const Schema = mongoose.Schema;

const campaignSchema = new Schema({
  campaignId: { type: String, unique: true, required: true },
  name: { type: String, required: true },
  type: { 
    type: String, 
    enum: ['邮件营销', '短信营销', '电话营销'], 
    required: true 
  },
  status: { 
    type: String, 
    enum: ['草稿', '进行中', '已完成', '已暂停'], 
    default: '草稿' 
  },
  content: {
    subject: { type: String },
    body: { type: String },
    template: { type: String }
  },
  startDate: { type: Date },
  endDate: { type: Date },
  createdBy: { type: mongoose.Schema.Types.ObjectId, ref: 'Admin' },
  createTime: { type: Date, default: Date.now }
});

// 创建索引
campaignSchema.index({ campaignId: 1 });
campaignSchema.index({ type: 1 });
campaignSchema.index({ status: 1 });
campaignSchema.index({ createdBy: 1 });
campaignSchema.index({ startDate: 1 });
campaignSchema.index({ endDate: 1 });
campaignSchema.index({ createTime: -1 });

// 营销活动目标客户关联表
const campaignTargetSchema = new Schema({
  campaignId: { type: mongoose.Schema.Types.ObjectId, ref: 'Campaign', required: true },
  customerId: { type: mongoose.Schema.Types.ObjectId, ref: 'Customer', required: true },
  status: { 
    type: String, 
    enum: ['待发送', '已发送', '已打开', '已点击', '已回复', '失败'], 
    default: '待发送' 
  },
  sentTime: { type: Date },
  openTime: { type: Date },
  clickTime: { type: Date },
  createTime: { type: Date, default: Date.now }
});

// 创建营销目标索引
campaignTargetSchema.index({ campaignId: 1 });
campaignTargetSchema.index({ customerId: 1 });
campaignTargetSchema.index({ status: 1 });
campaignTargetSchema.index({ sentTime: 1 });

const Campaign = mongoose.model("Campaign", campaignSchema);
const CampaignTarget = mongoose.model("CampaignTarget", campaignTargetSchema);

module.exports = {
  Campaign,
  CampaignTarget
};